import 'package:draggable_scrollbar/draggable_scrollbar.dart';
import 'package:flutter/widgets.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../public.dart';
import 'components/item.dart';

class BookInfoPage extends StatefulWidget {
  final String title;
  final String url;
  final String author;
  final String now;
  final String reptileType;
  final String reptileType1;
  BookInfoPage(
      {String title,
      String url,
      String author,
      String now,
      String reptileType,
      String reptileType1})
      : this.title = title ?? "",
        this.url = url ?? "",
        this.author = author ?? "",
        this.now = now ?? "",
        this.reptileType = reptileType ?? "",
        this.reptileType1 = reptileType1 ?? "";

  @override
  _BookInfoPageState createState() => _BookInfoPageState();
}

class _BookInfoPageState extends State<BookInfoPage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  ScrollController _customController = ScrollController();

//  HideAlways
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      child: ProviderWidget<BookInfoModel>(
        model: BookInfoModel(Provider.of<ThemeModel>(context)),
        onModelReady: (model) async => model.initData(
            title: widget.title,
            url: widget.url,
            author: widget.author,
            now: widget.now.toString(),
            reptileType: widget.reptileType,
            reptileType1: widget.reptileType1),
        builder: (context, model, child) {
          return Scaffold(
            appBar: PreferredSize(
              preferredSize: Size.fromHeight(
                  ScreenUtil().setHeight(44) + ScreenUtil.statusBarHeight),
              child: AppBar(
                centerTitle: true,
                title: Text(model.title + model.now),
              ),
            ),
            body: () {
              if (model.busy) {
                return ViewStateBusyWidget();
              } else if (model.error) {
                return ViewStateWidget(onPressed: model.initData);
              } else if (model.empty) {
                return ViewStateEmptyWidget();
              } else {
                return Stack(
                  children: <Widget>[
                    Container(
                      color: model.themeModel.customThemeData.mainColor,
                      child: Column(
                        children: <Widget>[
                          Container(
                            width: ScreenUtil().setWidth(750),
                            height: ScreenUtil().setHeight(250),
                            color: model.themeModel.customThemeData.mainColor,
                            child: Item(model: model),
                          ),
                          Container(
                            width: ScreenUtil().setWidth(750),
                            height: ScreenUtil().setHeight(1334) -
                                ScreenUtil().setHeight(44) -
                                ScreenUtil.statusBarHeight -
                                ScreenUtil.statusBarHeight -
                                ScreenUtil().setHeight(250),
                            child: DraggableScrollbar(
                              controller: _customController,
                              child: ListView.builder(
                                controller: _customController,
                                itemCount: model.bookInfo.list.length,
                                itemBuilder: (context, index) {
                                  return _buildChapter(
                                      model, model.bookInfo.list[index], index);
                                },
                              ),
                              heightScrollThumb: 48.0,
                              backgroundColor: model.themeModel.customThemeData
                                  .mainBackgroundColor,
                              scrollThumbBuilder: (
                                Color backgroundColor,
                                Animation<double> thumbAnimation,
                                Animation<double> labelAnimation,
                                double height, {
                                Text labelText,
                                BoxConstraints labelConstraints,
                              }) {
                                return FadeTransition(
                                  opacity: thumbAnimation,
                                  child: Container(
                                    height: height,
                                    width: 20.0,
                                    decoration: BoxDecoration(
                                        color: backgroundColor,
                                        borderRadius: BorderRadius.all(
                                            Radius.circular(20))),
                                  ),
                                );
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                    Positioned(
                      bottom: ScreenUtil().setHeight(0),
                      left: ScreenUtil().setWidth(0),
                      right: ScreenUtil().setWidth(0),
                      child: Container(
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(0)),
                            boxShadow: [
                              BoxShadow(
                                color: Color(0xFF222426),
                                blurRadius: 5,
                              )
                            ]),
                        child: ClipRRect(
                          clipBehavior: Clip.antiAliasWithSaveLayer,
                          borderRadius: BorderRadius.circular(0),
                          child: Material(
                            child: Ink(
                              color: model.now != "0"
                                  ? model.themeModel.customThemeData
                                      .mainUnActiveColor
                                      .withRed(50)
                                  : model.themeModel.customThemeData
                                      .mainUnActiveColor
                                      .withRed(50),
                              child: InkWell(
                                highlightColor: model
                                    .themeModel.customThemeData.mainColor
                                    .withRed(50),
                                splashColor: model
                                    .themeModel.customThemeData.mainColor
                                    .withRed(50),
                                onTap: () async {
                                  Chapter chapter = model.findChapter();
                                  String bookId =
                                      Uri.encodeComponent(chapter.bookId);
                                  String catalogId =
                                      Uri.encodeComponent(chapter.catalogId);
                                  String num = Uri.encodeComponent(chapter.num);
                                  String position = Uri.encodeComponent("0");
                                  var route = "/reader?"
                                      "bookId=$bookId&"
                                      "catalogId=$catalogId&"
                                      "num=$num&"
                                      "position=$position";
                                  bool isExist = await DatabaseHelper()
                                      .bookExist(
                                          chapter.bookId, widget.reptileType);
                                  if (!isExist) {
                                    DatabaseHelper().insertBook(
                                        bookId: chapter.bookId,
                                        bookName: widget.title,
                                        author: widget.author,
                                        description:
                                            model.bookInfo.book.description,
                                        imgUrl: model.bookInfo.book.imgUrl,
                                        baseUrl: model.bookInfo.book.baseUrl,
                                        originUrl:
                                            model.bookInfo.book.originUrl,
                                        url: model.bookInfo.book.url,
                                        updateTime:
                                            model.bookInfo.book.updateTime,
                                        bookType: model.bookInfo.book.bookType,
                                        bookStatus:
                                            model.bookInfo.book.bookStatus,
                                        reptileType:
                                            model.bookInfo.book.reptileType,
                                        total: model.bookInfo.list.length,
                                        now: int.parse(model.now),
                                        position: 0);
                                  }

                                  FlutterStatusbarManager.setFullscreen(true);
                                  FlutterStatusbarManager.setHidden(true);
                                  AppConfig.router.navigateTo(context, route,
                                      replace: false,
                                      transition: TransitionType.inFromBottom);
                                },
                                child: Container(
                                  child: Text(
                                    int.parse(widget.now) > 0 ? "继续阅读" : "开始阅读",
                                    style: TextStyle(
                                        color: model.themeModel.customThemeData
                                            .mainTextColor
                                            .withOpacity(0.7)),
                                    textAlign: TextAlign.center,
                                  ),
                                  padding: EdgeInsets.fromLTRB(
                                      ScreenUtil().setWidth(30),
                                      ScreenUtil().setWidth(30),
                                      ScreenUtil().setWidth(30),
                                      ScreenUtil().setWidth(30)),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    )
                  ],
                );
              }
            }(),
          );
        },
      ),
    );
  }

  Widget _buildChapter(BookInfoModel model, Chapter chapter, int index) {
    var item = Column(
      children: <Widget>[
        Container(
          decoration: BoxDecoration(
              border: Border(
                  bottom: BorderSide(
                      color: model.themeModel.customThemeData.mainUnActiveColor,
                      width: 0.1))),
          child: Ink(
            child: InkWell(
              onTap: () async {
                String bookId = Uri.encodeComponent(chapter.bookId);
                String catalogId = Uri.encodeComponent(chapter.catalogId);
                String num = Uri.encodeComponent(chapter.num);
                String position = Uri.encodeComponent("0");
                var route = "/reader?"
                    "bookId=$bookId&"
                    "catalogId=$catalogId&"
                    "num=$num&"
                    "position=$position";
                bool isExist = await DatabaseHelper()
                    .bookExist(chapter.bookId, widget.reptileType);
                if (!isExist) {
                  DatabaseHelper().insertBook(
                      bookId: chapter.bookId,
                      bookName: widget.title,
                      author: widget.author,
                      description: model.bookInfo.book.description,
                      imgUrl: model.bookInfo.book.imgUrl,
                      baseUrl: model.bookInfo.book.baseUrl,
                      originUrl: model.bookInfo.book.originUrl,
                      url: model.bookInfo.book.url,
                      updateTime: model.bookInfo.book.updateTime,
                      bookType: model.bookInfo.book.bookType,
                      bookStatus: model.bookInfo.book.bookStatus,
                      reptileType: model.bookInfo.book.reptileType,
                      total: model.bookInfo.list.length,
                      now: index,
                      position: 0);
                }

                FlutterStatusbarManager.setFullscreen(true);
                FlutterStatusbarManager.setHidden(true);
                AppConfig.router.navigateTo(context, route,
                    replace: false, transition: TransitionType.inFromBottom);
              },
              child: Row(
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.fromLTRB(20, 15, 0, 15),
                    child: Text(
                      chapter.name,
                      style: TextStyle(
                          fontSize: ScreenUtil().setSp(24),
                          color: model
                              .themeModel.customThemeData.mainUnActiveColor),
                    ),
                  )
                ],
              ),
            ),
          ),
        )
      ],
    );
    return item;
  }
}
